package com.lanchetech.user.service.impl;


import com.alibaba.excel.util.CollectionUtils;
import com.lanchetech.bean.response.HomeInfoResp;
import com.lanchetech.bean.response.ResultData;
import com.lanchetech.bean.vo.ZoneVO;
import com.lanchetech.common.enums.*;
import com.lanchetech.dao.*;
import com.lanchetech.entity.*;
import com.lanchetech.service.DaoService;
import com.lanchetech.user.service.HomeService;
import com.lanchetech.user.service.ProductService;
import com.lanchetech.user.service.WebService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;

@Service
public class HomeServiceImpl implements HomeService {

    @Autowired
    BannerMapper bannerMapper;

    @Autowired
    NavigationMapper navigationMapper;

    @Autowired
    WebConfigMapper webConfigMapper;

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    CategoryMapper categoryMapper;

    @Autowired
    PackagesMapper packagesMapper;

    @Autowired
    AdvertisementMapper advertisementMapper;

    @Autowired
    AdvertisementReadMapper advertisementReadMapper;

    @Autowired
    WebService webService;

    @Autowired
    ShoppingCartMapper shoppingCartMapper;

    @Autowired
    CourseMapper courseMapper;

    @Autowired
    ColumnsMapper columnsMapper;

    @Autowired
    CourseStudyMapper courseStudyMapper;

    @Autowired
    UserMapper userMapper;

    @Autowired
    DaoService daoService;

    @Autowired
    ColumnCourseCollectMapper columnCourseCollectMapper;

    @Autowired
    ArticleMapper articleMapper;

    @Autowired
    HipoConfigMapper hipoConfigMapper;

    @Autowired
    SpuMapper spuMapper;

    @Autowired
    VideoMapper videoMapper;

    @Autowired
    ProductService productService;



    @Override
    public ResultData<List<Banner>> getBanner(Integer scene) {
        return new ResultData<>(bannerMapper.findAllByScene(scene));
    }

    @Override
    public ResultData<List<Navigation>> getNavigation(Integer scene) {
        return new ResultData<>(navigationMapper.findAllByScene(scene));
    }

    private List<ColumnCourseCollect> getCollectList(List<Columns> list, User user) {
        if(user != null){
            if(!CollectionUtils.isEmpty(list)){
                List<Long> columnIds = new ArrayList<>();
                list.stream().forEach(item->{
                    if(ColumnsTypeEnum.CATALOG.getType().equals(item.getType())){
                        columnIds.add(item.getId());
                    }
                });
                if(columnIds.size() > 0){
                    return columnCourseCollectMapper.findAllByUserIdAndColumnIds(user.getId(), columnIds);
                }
            }
        }
        return null;
    }

    @Override
    public ResultData<HomeInfoResp> getHomeInfo(User user) {
        ValueOperations<String, HomeInfoResp> operations = redisTemplate.opsForValue();
        HomeInfoResp resp = new HomeInfoResp();
        if(user != null){
            // 获取最近一条未读的广告弹窗，若存在，则创建直接创建已读记录；
            Advertisement advertisement = advertisementMapper.findOneByNow(new Date());
            if(advertisement != null){
                // 判断是否已读
                if(advertisementReadMapper.findOneByUserIdAndAdvertisementId(user.getId(), advertisement.getId()) == null){
                    resp.setAdvertisement(advertisement);
                    // 创建广告已读记录
                    advertisementReadMapper.insert(AdvertisementRead.builder()
                            .userId(user.getId())
                            .advertisementId(advertisement.getId())
                            .createdAt(new Date())
                            .build());
                }
            }

            resp.setShoppingCartCount(shoppingCartMapper.sumByUserId(user.getId()));
        }

        HomeInfoResp cache = operations.get("HomeInfoResp");
        if (cache != null) {
            cache.setAdvertisement(resp.getAdvertisement());
            cache.setShoppingCartCount(resp.getShoppingCartCount());
            cache.setCollectList(getCollectList(cache.getColumnsList(), user));
            return new ResultData<>(cache);
        }

        Map<String, String> config = daoService.getHipoConfigMap();

        resp.setBannerList(bannerMapper.findAll());
        resp.setNavigationList(navigationMapper.findAll());
        resp.setHotSearch(webConfigMapper.findValueByName(WebConfigEnum.HOT_SEARCH.getConfig()));
        resp.setTagSearch(webConfigMapper.findValueByName(WebConfigEnum.TAG_SEARCH.getConfig()));
        Category category = new Category().setLevel(0);
        resp.setCategoryList(categoryMapper.findAllBackCategoryList(category));
        resp.setPackageList(packagesMapper.findTwoTop());

        List<Long> spuIds = new ArrayList<>();
        spuIds.add(Long.valueOf(config.get(HipoConfigEnum.MEMBER_SPU.getConfig())));
        spuIds.add(Long.valueOf(config.get(HipoConfigEnum.PARTNER_SPU.getConfig())));
        spuIds.add(Long.valueOf(config.get(HipoConfigEnum.SHAREHOLDER_SPU.getConfig())));
        Map<Long,Spu> spuMap = daoService.getSpuMap(spuIds);

        resp.setMemberSpu(spuMap.get(Long.valueOf(config.get(HipoConfigEnum.MEMBER_SPU.getConfig()))));
//        resp.setPartnerSpu(spuMap.get(Long.valueOf(config.get(HipoConfigEnum.PARTNER_SPU.getConfig()))));
        resp.setPartnerSpu(spuMap.get(Long.valueOf(config.get(HipoConfigEnum.SHAREHOLDER_SPU.getConfig()))));
        resp.setShareholderSpu(spuMap.get(Long.valueOf(config.get(HipoConfigEnum.SHAREHOLDER_SPU.getConfig()))));

        // 获取自定义专题
        String customId = webConfigMapper.findValueByName(WebConfigEnum.HOME_CUSTOM_PAGE.getConfig());
        if(customId != null){
            resp.setCustomData(webService.getCustomPageDetail(Long.valueOf(customId)).getValue());
        }

        // 获取首页专区
        String zoneId = webConfigMapper.findValueByName(WebConfigEnum.HOME_ZONE_ID.getConfig());
        if(zoneId != null){
            resp.setZoneVO(productService.getZoneSpuDetail(Long.valueOf(zoneId)).getValue());
        }else{
            resp.setZoneVO(new ZoneVO());
        }

        //版本号
        resp.setVersion(webConfigMapper.findValueByName(WebConfigEnum.VERSION.getConfig()));

        //安卓下载链接
        resp.setAndroidDownloadUrl(webConfigMapper.findValueByName(WebConfigEnum.ANDROID_DOWNLOAD_URL.getConfig()));

        //邀请新人配置
        resp.setInviteL1Count(config.get(HipoConfigEnum.INVITE_L1_COUNT.getConfig()));
        resp.setInviteL2Count(config.get(HipoConfigEnum.INVITE_L2_COUNT.getConfig()));
        resp.setInviteL1Reward(config.get(HipoConfigEnum.INVITE_L1_REWARD.getConfig()));
        resp.setInviteL2Reward(config.get(HipoConfigEnum.INVITE_L2_REWARD.getConfig()));

        //会员等级嗨币奖励
        resp.setCardPointV1Rate(config.get(HipoConfigEnum.DIRECT_CARD_POINT_V1_RATE.getConfig()));
        resp.setCardPointV2Rate(config.get(HipoConfigEnum.DIRECT_CARD_POINT_V2_RATE.getConfig()));
        resp.setCardPointV3Rate(config.get(HipoConfigEnum.DIRECT_CARD_POINT_V3_RATE.getConfig()));

        operations.set("HomeInfoResp", resp, 10, TimeUnit.MINUTES);

        return new ResultData<>(resp);
    }

    @Override
    public ResultData<HomeInfoResp> getHomeCustom(User user) {
        ValueOperations<String, HomeInfoResp> operations = redisTemplate.opsForValue();
        HomeInfoResp resp = new HomeInfoResp();
        if(user != null){
            // 获取最近一条未读的广告弹窗，若存在，则创建直接创建已读记录；
            Advertisement advertisement = advertisementMapper.findOneByNow(new Date());
            if(advertisement != null){
                // 判断是否已读
                if(advertisementReadMapper.findOneByUserIdAndAdvertisementId(user.getId(), advertisement.getId()) == null){
                    resp.setAdvertisement(advertisement);
                    // 创建广告已读记录
                    advertisementReadMapper.insert(AdvertisementRead.builder()
                            .userId(user.getId())
                            .advertisementId(advertisement.getId())
                            .createdAt(new Date())
                            .build());
                }
            }
            Long sum = shoppingCartMapper.sumByUserId(user.getId());
            resp.setShoppingCartCount(sum);
        }

        HomeInfoResp cache = operations.get("HomeCustomResp");
        if (cache != null) {
            cache.setAdvertisement(resp.getAdvertisement());
            cache.setShoppingCartCount(resp.getShoppingCartCount());
            return new ResultData<>(cache);
        }

        resp.setHotSearch(webConfigMapper.findValueByName(WebConfigEnum.HOT_SEARCH.getConfig()));

        // 获取自定义专题
        WebConfig webConfig = webConfigMapper.findOneByName(WebConfigEnum.HOME_CUSTOM_PAGE.getConfig());
        if(webConfig != null && webConfig.getValue() != null){
            resp.setCustomData(webService.getCustomPageDetail(Long.valueOf(webConfig.getValue())).getValue());
        }

        operations.set("HomeCustomResp", resp, 10, TimeUnit.MINUTES);

        return new ResultData<>(resp);
    }



}